package br.com.estagio.domain.dao;

import java.util.List;

import javax.persistence.EntityManager;

import br.com.estagio.domain.entity.EntityAbstract;
import br.com.estagio.filter.EntityManagerUtil;

public abstract class Dao {

	protected EntityManager manager;
	
	public Dao() {
//		FacesContext fc = FacesContext.getCurrentInstance();
//		ExternalContext ec = fc.getExternalContext();
//		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
//		this.manager = (EntityManager) request.getAttribute("EntityManager");
		this.manager = EntityManagerUtil.getEntityManager();
	}

	public EntityManager getManager() {
//		if ((this.manager != null) && (this.manager.isOpen())) {
//			this.manager.getTransaction().begin();
//		} else {
//			this.manager = EntityManagerUtil.getEntityManager();
//		}
//		return this.manager;
		
		if ((this.manager == null) || (!this.manager.isOpen())) {
			this.manager = EntityManagerUtil.getEntityManager();
		}
		if (!this.manager.getTransaction().isActive()) {
			this.manager.getTransaction().begin();
		}
		return this.manager;
	}
	
	public void insert(EntityAbstract entity) {
		this.update(entity);
	}
	
	public void remove(Integer id) {
		try {
			EntityAbstract entity = this.findById(id);
			this.getManager().remove(entity);
			this.commit();
		} catch (Exception e) {
			this.rollback();
			e.printStackTrace();
		}	
	}
	
	public void update(EntityAbstract entity) {
		try {
			this.getManager().merge(entity);
			this.commit();
		} catch (Exception e) {
			this.rollback();
			e.printStackTrace();
		}		
	}
	
	public EntityAbstract findById(Integer id) {
		try {
			return this.getManager().find(EntityAbstract.class, id);
		} catch (Exception e) {
			this.rollback();
			e.printStackTrace();			
		}		
		return null;
	}
	
	public abstract List listAll();
	
	public void commit() {
		if ((this.manager != null) 
				&& (this.manager.getTransaction().isActive())) {
			this.manager.getTransaction().commit();
		}
	}
	
	public void rollback() {
		if ((this.manager != null) 
				&& (this.manager.getTransaction().isActive())) {
			this.manager.getTransaction().rollback();
		}
	}
}
